package github_sdk

import (
	"context"
	"devops/pkg/git/git_model"

	"github.com/google/go-github/v34/github"
	"golang.org/x/oauth2"
)

//const GithubToken = "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"

type githubClient struct {
	g *github.Client
}

func NewGithubClient(token string) *githubClient {
	ctx := context.Background()
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
	tc := oauth2.NewClient(ctx, ts)
	client := github.NewClient(tc)
	return &githubClient{g: client}
}

func (github *githubClient) GetRepos() ([]git_model.Repo, error) {
	githubRepos, _, err := github.g.Repositories.List(context.Background(), "", nil)
	if err != nil {
		return nil, err
	}
	repos := make([]git_model.Repo, 0, len(githubRepos))
	for _, githubRepo := range githubRepos {
		// description 可能为 nil
		desc := ""
		if githubRepo.Description != nil {
			desc = *githubRepo.Description
		}
		repo := git_model.Repo{
			FullName: *githubRepo.FullName,
			Name:     *githubRepo.Name,
			Owner: git_model.User{
				Login:     *githubRepo.Owner.Login,
				AvatarUrl: *githubRepo.Owner.AvatarURL,
				HtmlUrl:   *githubRepo.Owner.HTMLURL,
			},
			Path:        *githubRepo.Name,
			Description: desc,
			HtmlUrl:     *githubRepo.HTMLURL,
			CloneUrl:    *githubRepo.CloneURL,
		}
		repos = append(repos, repo)
	}
	return repos, nil
}

func (github *githubClient) GetBranches(owner string, repo string) []git_model.Branch {
	githubBranches, _, err := github.g.Repositories.ListBranches(context.Background(), owner, repo, nil)
	if err != nil {
		return nil
	}
	branches := make([]git_model.Branch, 0, len(githubBranches))
	for _, githubBranch := range githubBranches {
		b, _, _ := github.g.Repositories.GetBranch(context.Background(), owner, repo, *githubBranch.Name)
		branches = append(branches, git_model.Branch{Name: *b.Name, CommittedDate: git_model.CommittedDate(b.Commit.Commit.Committer.Date)})
	}
	return branches
}
